var findallsxlink = webrootpath+"gzkproperties/findallsxlink";     //获取所有属性
var insertaddgzlink = webrootpath+"gz/insertaddgzlink";     //新增规则
var updategzlink = webrootpath+"gz/updategzlink";//修改规则
var findrulelistbyrulelink = webrootpath+"gz/findrulelistbyrulelink";     //获取规则集下所有规则
var insertrulelistlink = webrootpath+"gz/insertrulelistlink";     //新增规则集
var updaterulelistlink = webrootpath+"gz/updaterulelistlink";//修改规则集

var rulelistid = sessionStorage.getItem("rulelistid"); //规则集id
var selectcateid = sessionStorage.getItem("selectcateid"); //选中分类id

var v_searchdetail_link = webrootpath+"gz/v_searchdetail_link";//查看规则细览
var v_gz_delete_link = webrootpath+"gz/v_gz_delete_link";//删除规则

var selgzjrulelink = webrootpath+"gz/selgzjrulelink";//判断传入的规则集id有没有内容
$(function () {
    findallsx(); //获取分类下所有的属性
    $("#editrule_content").val("");
    findrulelistbyrule(1);//获取规则集下所有的规则
    //判断规则集为修改还是添加
    selgzjrule();
});

/***
 * 判断传入的规则集id有没有内容
 */
function selgzjrule() {
    $.get(selgzjrulelink,{
        rulelistid:rulelistid
    },function (msg) {
        if(msg.code=="0"){
            //规则集下没有规则
            $("#scgzj_cont_id").show();
            $("#update_scgzj_cont_id").hide();
        }else if(msg.code=="1"){
            //赋值
            $("#rule_name").val(msg.data.listname);
            $("#rule_desc").val(msg.data.listdesc);
            $("#rule_priority").val(msg.data.listpriority);
            $("#rule_type").val(msg.data.listruletype);

            //规则集下存在规则
            $("#scgzj_cont_id").hide();
            $("#update_scgzj_cont_id").show();
            $("#update_scgzj_cont_id").click(function () {
                var rule_name = $.trim($("#rule_name").val());
                var rule_desc = $.trim($("#rule_desc").val());
                var rule_priority = $.trim($("#rule_priority").val());
                var rule_type = $.trim($("#rule_type").val());
                if(rule_name.length==0){
                    $.alert({content: '规则集名称不能为空'});
                    return false;
                }
                var ts = $.confirm({
                    title: '提示',
                    content: '您确定修改规则集吗？',
                    buttons: {
                        '确定': function () {
                            ts.close();
                            $.post(updaterulelistlink,{
                                rule_name:rule_name,
                                rule_desc:rule_desc,
                                rule_priority:rule_priority,
                                rule_type:rule_type,
                                rulelistid:rulelistid,
                                selectcateid:selectcateid
                            },function (content) {
                                if(content.code=="1"){
                                    window.opener.findgzjlist();

                                    var as = $.confirm({
                                        title: '提示',
                                        content: '操作成功',
                                        autoClose: '关闭|1500',
                                        buttons: {
                                            "关闭": function () {
                                                as.close();
                                                window.close();
                                            }
                                        }
                                    });
                                }else {
                                    var as = $.confirm({
                                        title: '提示',
                                        content: '操作失败',
                                        autoClose: '关闭|1500',
                                        buttons: {
                                            "关闭": function () {
                                                as.close();
                                            }
                                        }
                                    });
                                }
                            });
                        },
                        '取消': function () {
                            ts.close();
                        }
                    }
                });


            });
        }
    });
}

/****
 * 内容提交，生成规则文件
 */
function save_editure() {
    var rule_name = $.trim($("#rule_name").val());
    var rule_desc = $.trim($("#rule_desc").val());
    var rule_priority = $.trim($("#rule_priority").val());
    var rule_type = $.trim($("#rule_type").val());
    if(rule_name.length==0){
        $.alert({content: '规则集名称不能为空'});
        return false;
    }
    var ts = $.confirm({
        title: '提示',
        content: '您确定保存规则集吗？',
        buttons: {
            '确定': function () {
                ts.close();
                $.post(insertrulelistlink,{
                    rule_name:rule_name,
                    rule_desc:rule_desc,
                    rule_priority:rule_priority,
                    rule_type:rule_type,
                    rulelistid:rulelistid,
                    selectcateid:selectcateid
                },function (content) {
                    if(content.code=="1"){
                        window.opener.findgzjlist();
                        var as = $.confirm({
                            title: '提示',
                            content: '操作成功',
                            autoClose: '关闭|1500',
                            buttons: {
                                "关闭": function () {
                                    as.close();
                                    window.close();
                                }
                            }
                        });
                    }else {
                        var as = $.confirm({
                            title: '提示',
                            content: '操作失败',
                            autoClose: '关闭|1500',
                            buttons: {
                                "关闭": function () {
                                    as.close();
                                }
                            }
                        });
                    }
                });
            },
            '取消': function () {
                ts.close();
            }
        }
    });
}
/***
 * 保存规则
 */
function save_rule() {
    var model_frame_editrule_name = $.trim($("#model_frame_editrule_name").val());
    var model_frame_editrule_desc = $.trim($("#model_frame_editrule_desc").val());
    var model_frame_editrule_priority = $.trim($("#model_frame_editrule_priority").val());
    var editrule_content = $.trim($("#editrule_content").val());
    var r_map = "";
    $("#editrule_jieguo").find("tr").each(function (_index,_this) {
        var r_name = $.trim($(_this).find("td:eq(0)").text());
        var r_type = $.trim($(_this).find("td:eq(1)").text());
        var r_desc = $.trim($(_this).find("td:eq(2)").text());
        var r_value = $.trim($(_this).find("td:eq(3)").find("textarea").val());
        if(r_value.length>0){
            r_map+="|"+r_name+"^"+encodeURI(r_value);
        }
    });
    if(model_frame_editrule_name.length==0 || model_frame_editrule_desc.length==0){
        $.alert({
            title: '提示',
            content: '名称和描述不为空'
        });
        return false;
    }
    if(editrule_content.length==0){
        $.alert({
            title: '提示',
            content: '脚本内容必须存在值'
        });
        return false;
    }
    if (r_map==0){
        $.alert({
            title: '提示',
            content: '输出结果必须有一个值以上'
        });
        return false;
    }
    r_map = r_map.substring(1);
    var ts = $.confirm({
        title: '提示',
        content: '您确定提交规则吗？',
        buttons: {
            '确定': function () {
                $.post(insertaddgzlink,{
                    model_frame_editrule_name:model_frame_editrule_name,
                    model_frame_editrule_desc:model_frame_editrule_desc,
                    model_frame_editrule_priority:model_frame_editrule_priority,
                    editrule_content:editrule_content,
                    r_map:r_map,
                    rulelistid:rulelistid
                },function (content) {
                    if(content.code=='1'){
                        var as = $.confirm({
                            title: '提示',
                            content: '操作成功',
                            autoClose: '关闭|1500',
                            buttons: {
                                "关闭": function () {
                                    as.close();
                                    rule_tab(0);
                                    findrulelistbyrule(1);

                                }
                            }
                        });
                    }
                });
            },
            '取消': function () {
                ts.close();
            }
        }
    });





}
/***
 * 清空
 */
function rule_clear() {
    $("#editrule_content").val("");
}
/***
 * 并且关系
 */
function rule_and() {
    var valstr = $.trim($("#editrule_content").val());
    $("#editrule_content").val(valstr+" &&");
}
/***
 * 或者关系
 */
function rule_or() {
    var valstr = $.trim($("#editrule_content").val());
    $("#editrule_content").val(valstr+" ||");
}
/***
 * 条件应用
 * @param _pid
 */
function tiaojian_yingyong(_pid) {
    var tjid = "#tiaojian_tr_"+_pid;
    var pname = $(tjid).find("td:eq(0)").text();
    var ptj = $(tjid).find("td:eq(2)").find("select").val();
    var pval = $(tjid).find("td:eq(3)").find("input").val();
    var valstr = $.trim($("#editrule_content").val());
    if(ptj=='10'){
        //等于
        var res_str = pname+".equals(\""+pval+"\")";
        $("#editrule_content").val(valstr+" "+res_str);
    }else if(ptj=='20'){
        //非等于
        var res_str = "(!"+pname+".equals(\""+pval+"\"))";
        $("#editrule_content").val(valstr+" "+res_str);
    }else if(ptj=='30'){
        //包含于
        var res_str = pname+".contains(\""+pval+"\")";
        $("#editrule_content").val(valstr+" "+res_str);
    }else if(ptj=='40'){
        //不包含于
        var res_str = "(!"+pname+".contains(\""+pval+"\"))";
        $("#editrule_content").val(valstr+" "+res_str);
    }else if(ptj=='50'){
        //符合正则表达式
        var res_str = "("+pname+"~='"+pval+"')";
        $("#editrule_content").val(valstr+" "+res_str);
    }else{
        //基本关系运算符
        var res_str = pname+ptj+pval;
        $("#editrule_content").val(valstr+" "+res_str);


    }
}

/***
 * 获取条件属性
 */
function findallsx() {

    if (selectcateid!=undefined && selectcateid.length>0){
        $.get(findallsxlink,{selectcateid:selectcateid},function (content) {
            if (content.code=="1"){
                var dobjlist = content.data;
                var tiaojianhtml = "";
                var jieguohtml = "";
                for(var i in dobjlist){
                    var dobj = dobjlist[i];
                    var ttype = dobj.propertiestype;
                    if(ttype==10){
                        //条件
                        tiaojianhtml+="<tr id='tiaojian_tr_"+dobj.propertiesid+"'>" +
                        "<td>"+dobj.propertiesname+"</td>" +
                        "<td>"+dobj.propertiescontent+"</td>" +
                        "<td><select class=\"form-control\" >" +
                            "<option value='10'>等于（字符串类型）</option>" +
                            "<option value='20'>非等于（字符串类型）</option>" +
                            "<option value='30'>包含于（字符串类型）</option>" +
                            "<option value='40'>不包含于（字符串类型）</option>" +
                            "<option value='50'>符合正则表达式</option>" +
                            "<option value='=='>等于</option>" +
                            "<option value='>'>大于</option>" +
                            "<option value='>='>大于等于</option>" +
                            "<option value='<'>小于</option>" +
                            "<option value='<='>小于等于</option>" +
                            "<option value='!='>非等于</option>" +
                            "</select></td>" +
                        "<td><input type=\"text\" class=\"form-control\" id=\"name\" placeholder=\"请输入值\"></td>" +
                        "<td><button type=\"button\" class=\"btn btn-success\" onclick='tiaojian_yingyong(\""+dobj.propertiesid+"\")'>应用</button></td>" +
                        "</tr>";
                    }else if(ttype==20){
                        //结果
                        jieguohtml+="<tr >\n" +
                            "\t<td>"+dobj.propertiesname+"</td>\n" +
                            "\t<td>"+dobj.propertiescontent+"</td>\n" +
                            "\t<td>"+dobj.propertiesdesc+"</td>\n" +
                            "\t<td>\n" +
                            "\t\t\t<textarea class=\"form-control\" ></textarea>\n" +
                            "\t</td>\n" +
                            "</tr>";

                    }
                }
                $("#editrule_tiaojian").html(tiaojianhtml);
                $("#editrule_jieguo").html(jieguohtml);
            }else {
                $("#editrule_tiaojian").html("暂无数据");
                $("#editrule_jieguo").html("暂无数据");

            }
        })
    } 
}


/***
 * 规则执行状态导航
 * @param _index
 */
function rule_tab(_index) {
    $("#rule_ul li").removeClass("active");
    $("#rule_ul_cen_0").hide();
    $("#rule_ul_cen_1").hide();
    if(_index=="0"){
        $("#rule_ul li:eq(0)").addClass("active");
        $("#rule_ul_cen_0").show();
    }else if (_index=="1"){
        $("#rule_ul li:eq(1)").addClass("active");
        $("#rule_ul_cen_1").show();
        $("#model_frame_editrule_name").val("");
        $("#model_frame_editrule_desc").val("");
        $("#editrule_content").val("");
        $("#editrule_jieguo").find("tr").each(function (_index,_this) {
            $(_this).find("td:eq(3)").find("textarea").val("");
        });
        $("#insert_guize").show();
        $("#update_guize").hide();

    }
}

/***
 * 获取规则集下所有规则
 */
function findrulelistbyrule(_pagenum) {
    $.get(findrulelistbyrulelink,{
        rulelistid:rulelistid,
        pagenum:_pagenum
    },function (content) {
        if(content.code=='1'){
            var contentlist = content.data;
            var htmlstr = "";
            for(var i in contentlist){
                var dataobj = contentlist[i];
                htmlstr+="<tr>\n" +
                    "<td>"+i+"<input type='checkbox' /></td>\n" +
                    "<td>"+dataobj.modelname+"</td>\n" +
                    "<td>"+dataobj.modeldesc+"</td>\n" +
                    "<td>"+dataobj.modelpriority+"</td>\n" +
                    "<td>"+dataobj.crdate+"</td>\n" +
                    "<td><button type=\"button\" class=\"btn btn-info\" onclick='v_searchdetail(\""+dataobj.modelid+"\")'>查看详细</button>&nbsp;&nbsp;" +
                    "<button type=\"button\" class=\"btn btn-info\" onclick='v_updatedetail(\""+dataobj.modelid+"\")'>修改</button>&nbsp;&nbsp;" +
                    "<button type=\"button\" class=\"btn btn-danger\" onclick='v_gz_delete(\""+dataobj.modelid+"\")'>删除</button></td>\n" +
                    "</tr>";

            }
            findrulelistbyrule_pages(_pagenum,content.pages);
            $("#rule_ul_cen_0_content").html(htmlstr);
        }else {
            $("#rule_ul_cen_0_content").html("该规则集下暂时没有规则");
        }
    });
}
//数据分页
function findrulelistbyrule_pages(_pagenum,_pages){
    //处理分页
    $('#findrulelistbyrule_pages_id').bootstrapPaginator({
        currentPage: _pagenum,
        totalPages: _pages,
        size:"normal",
        bootstrapMajorVersion: 3,
        alignment:"right",
        numberOfPages:5,
        itemTexts: function (type, page, current) {
            switch (type) {
                case "first":
                    return "首页";
                case "prev":
                    return "上一页";
                case "next":
                    return "下一页";
                case "last":
                    return "末页";
                case "page":
                    return page;
            }
        },
        onPageClicked: function (event, originalEvent, type, page) {
            findrulelistbyrule(page);
        }
    });
}
/***
 * 修改规则
 * @param _modelid
 */
function v_updatedetail(_modelid) {
    rule_tab(1);
    //赋值
    $.get(v_searchdetail_link,{
        modelid:_modelid
    },function (msg) {
        if (msg.code=="1"){
            console.log(msg);
            var dataobj = msg.data;
            $("#model_frame_editrule_name").val(dataobj.modelname);
            $("#model_frame_editrule_desc").val(dataobj.modeldesc);
            $("#model_frame_editrule_priority").val(dataobj.modelpriority);
            $("#editrule_content").val(dataobj.modelinit);
            var modelresult =  decodeURI(dataobj.modelresult);
            var modelresultarray = modelresult.split("|");
            $("#editrule_jieguo").find("tr").each(function (_index,_this) {
                var r_name = $.trim($(_this).find("td:eq(0)").text());
                var r_type = $.trim($(_this).find("td:eq(1)").text());
                var r_desc = $.trim($(_this).find("td:eq(2)").text());
                for (var i in modelresultarray){
                    var objs = modelresultarray[i];
                    var objarray =  objs.split("^");
                    if (objarray.length==2){
                        if(r_name==objarray[0]){
                            $(_this).find("td:eq(3)").find("textarea").val(objarray[1]);
                        }
                    }
                }

            });
        }
    });
    //改变按钮
    $("#update_guize").show();
    $("#insert_guize").hide();
    $("#update_guize").click(function () {
        //点击提交修改规则

        var model_frame_editrule_name = $.trim($("#model_frame_editrule_name").val());
        var model_frame_editrule_desc = $.trim($("#model_frame_editrule_desc").val());
        var model_frame_editrule_priority = $.trim($("#model_frame_editrule_priority").val());
        var editrule_content = $.trim($("#editrule_content").val());
        var r_map = "";
        $("#editrule_jieguo").find("tr").each(function (_index,_this) {
            var r_name = $.trim($(_this).find("td:eq(0)").text());
            var r_type = $.trim($(_this).find("td:eq(1)").text());
            var r_desc = $.trim($(_this).find("td:eq(2)").text());
            var r_value = $.trim($(_this).find("td:eq(3)").find("textarea").val());
            if(r_value.length>0){
                r_map+="|"+r_name+"^"+encodeURI(r_value);
            }
        });
        if(model_frame_editrule_name.length==0 || model_frame_editrule_desc.length==0){
            $.alert({
                title: '提示',
                content: '名称和描述不为空'
            });
            return false;
        }
        if(editrule_content.length==0){
            $.alert({
                title: '提示',
                content: '脚本内容必须存在值'
            });
            return false;
        }
        if (r_map==0){
            $.alert({
                title: '提示',
                content: '输出结果必须有一个值以上'
            });
            return false;
        }
        r_map = r_map.substring(1);
        var ts = $.confirm({
            title: '提示',
            content: '您确定修改规则吗？',
            buttons: {
                '确定': function () {
                    $.post(updategzlink,{
                        model_frame_editrule_name:model_frame_editrule_name,
                        model_frame_editrule_desc:model_frame_editrule_desc,
                        model_frame_editrule_priority:model_frame_editrule_priority,
                        editrule_content:editrule_content,
                        r_map:r_map,
                        rulelistid:rulelistid,
                        modelid:_modelid
                    },function (content) {
                        if(content.code=='1'){
                            var as = $.confirm({
                                title: '提示',
                                content: '操作成功',
                                autoClose: '关闭|1500',
                                buttons: {
                                    "关闭": function () {
                                        as.close();
                                        rule_tab(0);
                                        findrulelistbyrule(1);

                                    }
                                }
                            });
                        }
                    });
                },
                '取消': function () {
                    ts.close();
                }
            }
        });


    });


}


/***
 * 删除规则
 * */
function v_gz_delete(_modelid) {
    var opensearchlistid = sessionStorage.getItem("opensearchlistid");
    $.confirm({
        title:"提示",
        content:"您确定删除此规则吗？",
        buttons:{
            "确定":function () {
                $.get(v_gz_delete_link,{
                    modelid:_modelid,
                    opensearchlistid:opensearchlistid
                },function (msg) {
                    if (msg.code=='1'){
                        findrulelistbyrule(1);
                        $.alert(msg.msg,"提示");
                    }
                });
            },
            "取消":function () {

            }
        }
    });


}


/***
 * 查看详细
 * @param _modelid
 */
function v_searchdetail(_modelid) {
    $("#myModal").modal('show');
    $.get(v_searchdetail_link,{
        modelid:_modelid
    },function (msg) {
        if (msg.code=="1"){
            var dataobj = msg.data;
            $("#myModalLabel").html(dataobj.modelname);
            $("#zhixingtiaojian").html(dataobj.modelinit);
            var modelresult =  decodeURI(dataobj.modelresult);

            var modelresultarray = modelresult.split("|");

            var htmlstr = "";
            for (var i in modelresultarray){
                var objs = modelresultarray[i];
                var objarray =  objs.split("^");
                if (objarray.length==2){
                    htmlstr += "<tr>" +
                        "<td>"+objarray[0]+"</td>" +
                        "<td>"+objarray[1]+"</td>" +
                        "</tr>";
                }else if (objarray.length==1){
                    htmlstr += "<tr>" +
                        "<td>"+objarray[0]+"</td>" +
                        "<td>"+objarray[1]+"</td>" +
                        "</tr>";
                }
            }
            $("#zhixingdongzuo").html("<table class=\"table\"><caption>结果输出</caption><tbody>"+htmlstr+"</tbody></table>");
        }

    });
}